<template>
    <div class="header">
        <!-- 左侧：Logo和系统名称 -->
        <div class="header__left">
            <div class="header__logo">
                <img :src="logoSrc"  class="header__logo-image" />
            </div>
            <div class="header__system-name">
                <span class="header__system-title">{{ systemName }}</span>
            </div>
        </div>

        <!-- 右侧：个人头像 -->
        <div class="header__right">
            <SearchBox @search-result-click="handleSearchResultClick" />
            <div class="header__tools">
                <div v-for="item in toolList" :key="item.id" class="header__tool-item"
                    :class="{ 'header__tool-item--active': isToolActive(item.id) }">
                    <Popover v-if="item.id == 'common'" position="bottom" trigger="click" ref="commonPopoverRef"
                        :showArrow="false" customClass="header-common-popover" :offset="[0, 3]"
                        @visible-change="handleCommonPopoverChange">
                        <template v-slot:reference>
                            <span class="un-user_select">{{ item.name }}</span>
                        </template>
                        <QuickActionsPanel @close="handleCommonPopoverClose" />
                    </Popover>
                    <span v-else @click="item.click" class="un-user_select">{{ item.name }}</span>
                </div>
            </div>

            <Popover position="bottomRight" trigger="click" ref="userPopoverRef" :showArrow="false"
                customClass="user-popover" :offset="[0, -13]" @visible-change="handleUserPopoverChange">
                <template v-slot:reference>
                    <div class="header__user-avatar">
                        <img :src="userAvatar" class="header__avatar-image" />
                        <span class="header__user-name">{{ userName }}</span>
                    </div>
                </template>
                <UserInfoPanel :userName="userName" :userAvatar="userAvatar" 
                    :userOrganization="userOrganization" @personal-settings="handlePersonalSettings"
                    @logout="handleLogout" />
            </Popover>
        </div>
        <!-- 快捷功能抽屉 -->
        <QuickDrawer v-model:visible="quickDrawerVisible" @close="handleQuickDrawerClose"
            @item-click="handleQuickItemClick" />
        <!-- 通知消息抽屉 -->
        <NoticeDrawer v-model:visible="noticeDrawerVisible" @close="handleNoticeDrawerClose"
            @notice-click="handleNoticeClick" />
    </div>
</template>

<script setup>
import SearchBox from '@/components/pc/SearchBox.vue'
import QuickDrawer from '@/components/pc/drawer/QuickDrawer.vue'
import NoticeDrawer from '@/components/pc/drawer/NoticeDrawer.vue'
import QuickActionsPanel from '@/components/pc/QuickActionsPanel.vue'
import UserInfoPanel from '@/components/pc/UserInfoPanel.vue'
import { ref, onMounted, nextTick, computed, watch } from 'vue'
import { useRoute } from 'vue-router'
import Popover from '@/components/common/Popover.vue'
import { eventBus } from '@/service/eventService'
import { ROUTES } from '@/constants/routes.js'
import { navigateToMenuByConfig } from '@/service/funcMenuService'


const props = defineProps({
    // 系统名称
    systemName: {
        type: String,
        default: '系统名称'
    },
    // Logo 图片路径
    logoSrc: {
        type: String,
        default: '/favicon.ico'
    },
    // 用户名
    userName: {
        type: String,
        default: '用户名'
    },
    // 用户头像
    userAvatar: {
        type: String,
        default: '/favicon.ico'
    },
    // 用户组织
    userOrganization: {
        type: String,
        default: '默认组织-集团'
    }
})

// 定义事件
const emit = defineEmits(['personal-settings', 'logout'])

// 获取路由实例
const route = useRoute()

// 抽屉显示状态
const quickDrawerVisible = ref(false)
const noticeDrawerVisible = ref(false)


const initEventListeners = () => {
    eventBus.on('iframeClickEvent', () => {
        handleCommonPopoverClose()
        closeUserPopover()
    })
}

onMounted(() => {
    initEventListeners()

})
// 关闭所有抽屉的通用方法
const closeAllDrawers = () => {
    quickDrawerVisible.value = false
    noticeDrawerVisible.value = false
}
const hasDrawerOpen = () => {
    return quickDrawerVisible.value || noticeDrawerVisible.value
}

const openDrawer = async (drawerType) => {


    const isOpen = hasDrawerOpen()
    closeAllDrawers()

    if (isOpen) {
        await nextTick()
    }

    switch (drawerType) {
        case 'quick':
            quickDrawerVisible.value = true
            break
        case 'notice':
            noticeDrawerVisible.value = true
            break
    }
}
const commonPopoverRef = ref(null)
const commonPopoverVisible = ref(false)
const userPopoverRef = ref(null)
const userPopoverVisible = ref(false)

const handleCommonPopoverChange = (visible) => {
    commonPopoverVisible.value = visible
}

const handleUserPopoverChange = (visible) => {
    userPopoverVisible.value = visible
}

const handleCommonPopoverClose = () => {
    const instance = commonPopoverRef.value && commonPopoverRef.value[0]
    if (instance && instance.closePopover) {
        instance.closePopover()
    }
}

// 关闭用户弹窗的公共方法
const closeUserPopover = () => {
    const instance = userPopoverRef.value
    if (instance && instance.closePopover) {
        instance.closePopover()
    }
}

// 处理个人设置点击
const handlePersonalSettings = () => {
    emit('personal-settings')
    closeUserPopover()
}

// 处理退出点击
const handleLogout = () => {
    emit('logout')
    closeUserPopover()
}

const isToolActive = (toolId) => {
    switch (toolId) {
        case 'common':
            return commonPopoverVisible.value
        case 'quick':
            return quickDrawerVisible.value
        case 'notice':
            return noticeDrawerVisible.value
        default:
            return false
    }
}




// 基础工具列表
const baseToolList = [
    {
        id: 'common',
        name: '常用',
        icon: '',
    },
    {
        id: 'quick',
        name: '快捷',
        icon: '',
        click: () => {
            if (quickDrawerVisible.value) {
                quickDrawerVisible.value = false
                return
            }
            openDrawer('quick')
        }
    },
    {
        id: 'notice',
        name: '通知',
        icon: '',
        click: () => {
            if (noticeDrawerVisible.value) {
                noticeDrawerVisible.value = false
                return
            }
            openDrawer('notice')
        }
    },
]


const toolList = computed(() => {
    if (route.path === ROUTES.HARDCODE_WEB_BLANK) {
        return baseToolList.filter(item => item.id !== 'common')
    }
    return baseToolList
})

// 处理搜索结果点击
const handleSearchResultClick = (result) => {
    navigateToMenuByConfig(result.ID)
}

// 快捷抽屉事件处理
const handleQuickDrawerClose = () => {
    quickDrawerVisible.value = false
}

const handleQuickItemClick = (item) => {
    console.log('快捷功能点击:', item)
    // 这里可以添加路由跳转逻辑
}

// 通知抽屉事件处理
const handleNoticeDrawerClose = () => {
    noticeDrawerVisible.value = false
}

const handleNoticeClick = (notice) => {
    console.log('通知点击:', notice)
    // 这里可以添加通知处理逻辑
}
</script>

<style scoped lang="scss">
.header__tools {
    gap: 24px;
    padding: 0 17px;
    display: flex;
    box-shadow: 0 4px 12px 0 #ece9f0;
    border-radius: 40px;
    height: 38px;
    cursor: pointer;
    align-items: center;
    margin: 9px 0;
    background-color: #fff;
    color: #666;
}

.header__tool-item:hover {
    color: var(--theme-color);
}

.header__tool-item--active {
    color: var(--theme-color);
}

.header {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 12px;
    width: 100%;
    box-shadow: 0 0 12px 0 #ece9f0;
}

/* 头部左侧区域 */
.header__left {
    display: flex;
    align-items: center;
    gap: 8px;
}

.header__logo {
    display: flex;
    align-items: center;
}

.header__logo-image {
    width: 32px;
    height: 32px;
    border-radius: 4px;
}

.header__system-name {
    display: flex;
    align-items: center;
}

.header__system-title {
    font-size: 18px;
    font-weight: 700;
    color: rgba(0, 0, 0, .8);
    white-space: nowrap;

}

/* 头部右侧区域 */
.header__right {
    display: flex;
    gap: 16px;
    align-items: center;
}

.header__user-avatar {
    display: flex;
    box-shadow: 0 4px 12px 0 #ece9f0;
    border-radius: 40px;
    height: 38px;
    cursor: pointer;
    align-items: center;
    gap: 5px;
    margin: 9px 0;
    background-color: #fff;
    user-select: none;
}

.header__user-avatar:hover {
    background-color: rgba(0, 0, 0, 0.04);
}

.header__avatar-image {
    border-radius: 50px;
    border: 2px solid #f2f2f2;
    width: 36px;
    height: 36px;
    box-shadow: 0 4px 12px 0 #ece9f0;
    object-fit: cover;
}

.header__user-name {
    color: #666;
    font-size: 14px;
    font-style: normal;
    font-weight: 400;
    line-height: normal;
    padding-right: 16px;
    min-width: 32px;
    white-space: nowrap;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .header {
        padding: 0 12px;
    }

    .header__system-title {
        font-size: 16px;
    }

    .header__user-name {
        display: none;
        /* 移动端隐藏用户名 */
    }
}

@media (max-width: 480px) {
    .header__left {
        gap: 8px;
    }

    .header__logo-image {
        width: 28px;
        height: 28px;
    }

    .header__system-title {
        font-size: 14px;
    }
}
</style>

<style lang="scss">
/* 全局样式：自定义Popover样式 */
.custom-popover-body.header-common-popover {
    padding: 0;
    width: 297px;
    background-color: #fff;
    box-shadow: 0px 3px 6px 0px rgba(0, 0, 0, .15);
    border-radius: 4px;
    border: 1px solid #EBEEF5;
    overflow: hidden;
}
</style>